package com.uinnova.product.eam.service.asset.impl;

import com.binary.core.exception.BinaryException;
import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.comm.model.es.AssetChangeRecord;
import com.uinnova.product.eam.service.asset.AssetChangeRecordSvc;
import com.uinnova.product.eam.service.es.AssetChangeRecordDao;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.business.UserInfo;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author zdh_c
 */
@Service
public class AssetChangeRecordSvcImpl implements AssetChangeRecordSvc {
    @Resource
    AssetChangeRecordDao changeRecordDao;
    @Resource
    IUserApiSvc userApiSvc;
    @Override
    public Long saveChangeRecord(AssetChangeRecord changeRecord, String submitter) {
        BinaryUtils.checkEmpty(changeRecord,"变更流程信息");
        long timeMillis = System.currentTimeMillis();
        UserInfo userInfo = userApiSvc.getUserInfoByLoginCode(submitter);
        if (BinaryUtils.isEmpty(userInfo)) {
            throw new BinaryException("用户信息不存在");
        }
        if (BinaryUtils.isEmpty(changeRecord.getId())) {
            changeRecord.setSubmitter(userInfo.getUserName());
            changeRecord.setCreateTime(timeMillis);
        }
        changeRecord.setDomainId(userInfo.getDomainId());
        changeRecord.setModifyTime(timeMillis);
        return changeRecordDao.saveOrUpdate(changeRecord);
    }

    @Override
    public List<AssetChangeRecord> getAssetChangeRecordByCiCode(String ciCode) {
        BinaryUtils.checkEmpty(ciCode,"ciCode");
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery("ciCode.keyword", ciCode));
        query.must(QueryBuilders.termQuery("domainId", SysUtil.getCurrentUserInfo().getDomainId()));
        query.must(QueryBuilders.termQuery("state", 2));
        List<AssetChangeRecord> changeRecords = changeRecordDao.getListByQuery(query);
        if (CollectionUtils.isEmpty(changeRecords)) {
            return Collections.emptyList();
        }
        changeRecords.sort(Comparator.comparing(AssetChangeRecord::getModifyTime).reversed());
        return changeRecords;
    }

    @Override
    public AssetChangeRecord getById(Long id) {
        BinaryUtils.checkEmpty(id,"id");
        return changeRecordDao.getById(id);
    }
}
